package cn.j0n4than.accountingtool.controller.api;

import cn.j0n4than.accountingtool.config.ResponseConfig;
import cn.j0n4than.accountingtool.controller.common.BaseController;
import cn.j0n4than.accountingtool.entity.Active;
import cn.j0n4than.accountingtool.entity.User;
import cn.j0n4than.accountingtool.utils.Response;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 用户激活控制器
 *
 * @author jonathan
 */
@RestController
@RequestMapping("/api")
public class ActiveController extends BaseController {

    @GetMapping("/active/{id}")
    public Response active(@PathVariable String id) {
        Response response = Response.response();
        Active active = activeService.getActiveById(id);

        //没有这条数据
        if (active == null) {
            return response.setStatus(ResponseConfig.ERROR).setMessage("这里什么都没有");
        }

        //已经激活
        if (active.status) {
            return response.setStatus(ResponseConfig.SUCCESS).setMessage("你已经激活了你的账号");
        }

        //激活的业务逻辑
        active.status = true;
        User user = userService.getUserById(active.userId);
        user.emailVerifiedAt = new Date();
        if (activeService.update(active.id, active) > 0 && userService.update(user.id, user) > 0) {
            return response.setStatus(ResponseConfig.SUCCESS).setMessage("激活成功");
        } else {
            return response.setStatus(ResponseConfig.ERROR).setMessage("未知错误");
        }
    }
}
